using Core.Runtime;
using Cysharp.Threading.Tasks;
using UnityEngine;

namespace GameLauncher.Runtime
{
    public class AssetCheckState : HotFixState
    {
        public override async UniTask<StateResult> Execute()
        {
            mUpdateData = await RequestUpdateData();
            if (mUpdateData == null)
                return StateResult.Failure("获取更新数据失败,请检查网络");
            //TODO,需要添加App版本，可以用app版本增加，重置资源版本
            AssetManager.UpdateUriPrefix = $"{mUpdateData.HotFixServerURL}/{GameSettings.PlatformName}/{mUpdateData.ResVersion}";

            HotFixUI.RefreshDescLabel("正在检查资源版本...");
            var checkVersionResult = await AssetManager.CheckVersion();
            if (!checkVersionResult.Success)
            {
                HotFixUI.RefreshDescLabel("检查资源版本失败");
                return StateResult.Failure($"资源版本检查失败{checkVersionResult.Error}");
            }

            return StateResult.Success();
        }

        /// <summary>
        /// 请求UpdateData
        /// </summary>
        /// <returns></returns>
        private async UniTask<UpdateData> RequestUpdateData()
        {
            await UniTask.WaitForSeconds(0.2f);
            HotFixUI.RefreshDescLabel("正在请求更新数据...");
            var updateDataUrl = "http://150.158.54.69/UpdateData.txt";
            Debug.Log($"{updateDataUrl} 正在请求更新数据...");
            var updateDataWebResult = ""; //await Web.GetToString(updateDataUrl);
            if (string.IsNullOrEmpty(updateDataWebResult))
            {
                HotFixUI.RefreshDescLabel("更新数据请求失败,请检查网络");
                return null;
            }
            else
            {
                return JsonUtility.FromJson<UpdateData>(updateDataWebResult);
            }
        }

        private UpdateData mUpdateData;
    }
}